<template>
	<div>
		<el-breadcrumb separator-class="el-icon-arrow-right">
		  <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
		  <el-breadcrumb-item>权限管理</el-breadcrumb-item>
		  <el-breadcrumb-item>角色列表</el-breadcrumb-item>
		</el-breadcrumb>
		<!-- 卡片视图 -->
		<el-card>
			<!-- 添加角色按钮区域 -->
			<el-row>
				<el-col>
					<el-button type="primary" @click="AddRole">添加角色</el-button>
				</el-col>
			</el-row>
			<!-- 角色列表区域 -->
			<el-table :data="roleList" border stripe>
				<!-- 展开列 -->
				<el-table-column type="expand">
					<template v-slot="scope1">
						<el-row v-for="(item1,index1) in scope1.row.children" :key="item1.id"
						 :class="['bdbottom',index1===0?'bdtop':'','vcenter']" >
							<!-- 渲染一级权限 -->
							<el-col  :span="7">
								<el-tag closable @close="removeRightById(scope1.row,item1.id)">{{item1.authName}}</el-tag>
								<i class="el-icon-plus"></i>
							</el-col>
							<!-- 渲染二级 三级权限 -->
							<el-col :span="17"  >
								
								<el-row v-for="(item2,index2) in item1.children" :key="item2.id"
								 :class="['vcenter']">
									<el-col :span="12">
										
										<el-tag type="success" closable @close="removeRightById(scope1.row,item2.id)">{{item2.authName}}</el-tag>
										<i class="el-icon-plus"></i>
									</el-col>
									<el-col :span="12">
										<el-row>
											<el-col>
												<el-tag  type="warning"  v-for="(item3,index3) in item2.children" :key="item3.id"
												 closable @close="removeRightById(scope1.row,item3.id)">
												{{item3.authName}}</el-tag>
												
											</el-col>
										</el-row>
									</el-col>
								</el-row>
							</el-col>
							
						</el-row>
					</template>
				</el-table-column>
				<!-- 索引列 -->
				<el-table-column type="index" label="#"></el-table-column>
				<el-table-column label="角色名称" prop="roleName"></el-table-column>
				<el-table-column label="角色描述" prop="roleDesc"></el-table-column>
				<el-table-column label="操作" width="300px">
					<template v-slot="scope">
						<el-button size="mini" type="primary" icon="el-icon-edit"
						 @click="showEditDialog(scope.row)">编辑</el-button>
						<el-button size="mini" type="danger" icon="el-icon-delete"
						@click="showDeleteOpen(scope.row)">删除</el-button>
						<el-button size="mini" type="warning" icon="el-icon-setting" 
						@click="showSetRightDialog(scope.row)">分配权限</el-button>
					</template>
				</el-table-column>
			</el-table>
		</el-card>
		<!-- 分配权限 -->
		<el-dialog
		  title="分配权限"
		  :visible.sync="setRightDialogVisible"
		  width="50%" @close="setRightDialogClose">
			<!-- 树形控件 -->
		  <el-tree show-checkbox default-expand-all :default-checked-keys="defKeys"
			 node-key="id" :data="rightList" :props="treeProps" ref="treeRef"></el-tree>
		  <span slot="footer" class="dialog-footer">
		    <el-button @click="setRightDialogVisible = false">取 消</el-button>
		    <el-button type="primary" @click="allotRights">确 定</el-button>
		  </span>
		</el-dialog>
		<!-- 编辑 -->
		<el-dialog
		  title="编辑"
		  :visible.sync="EditDialogVisible"
		  width="50%" @close="setRightDialogClose">
			<el-form :model="EditRole" :rules="EditRoleRules" ref="EditRoleRef" label-width="70px">
			  <el-form-item label="名称" prop="roleName">
			    <el-input v-model="EditRole.roleName"></el-input>
			  </el-form-item>
				<el-form-item label="描述" prop="roleDesc">
				  <el-input v-model="EditRole.roleDesc"></el-input>
				</el-form-item>
			</el-form>
		  <span slot="footer" class="dialog-footer">
		    <el-button @click="EditDialogVisible = false">取 消</el-button>
		    <el-button type="primary" @click="EditRights">确 定</el-button>
		  </span>
		</el-dialog>
		<!-- 添加角色 -->
		<el-dialog
		  title="添加角色"
		  :visible.sync="AddDialogVisible"
		  width="50%" @close="setRightDialogClose">
			<el-form :model="EditRole" :rules="EditRoleRules" ref="EditRoleRef" label-width="70px">
			  <el-form-item label="名称" prop="roleName">
			    <el-input v-model="EditRole.roleName"></el-input>
			  </el-form-item>
				<el-form-item label="描述" prop="roleDesc">
				  <el-input v-model="EditRole.roleDesc"></el-input>
				</el-form-item>
			</el-form>
		  <span slot="footer" class="dialog-footer">
		    <el-button @click="AddDialogVisible = false">取 消</el-button>
		    <el-button type="primary" @click="AddRights">确 定</el-button>
		  </span>
		</el-dialog>
	
		
	</div>
</template>

<script>
	export default{
		data(){
			return{
				AddDialogVisible:false,
				EditRole:{
					
					roleName:'',
					roleDesc:''
				},
				RoleId:'',
				DeleteDialogVisible:false,
				EditDialogVisible:false,
				roleList:[],
				setRightDialogVisible:false,
				// 所有权限的数据
				rightList:[],
				treeProps:{
					label:'authName',
					children:'children'
				},
				//默认选中的节点di值数组
				defKeys:[],
				roleId:0,
				EditRoleRules:{
					roleName:[{required:true,message:'请输入角色名',trigger:'blur'}],
				}
			}
		},
		created() {
			this.getRolesList()
		},
		methods:{
			AddRole(){
				this.AddDialogVisible=true
			},
		async	AddRights(){
		const {data:res}	=await	this.$http.post(`roles`,this.EditRole)
	     console.log(res)
		if(res.meta.status!==201) return this.$message.error('添加失败')
		this.$message.success('添加成功')
		this.getRolesList()
		this.AddDialogVisible=false
			},
		async	EditRights(){
		const {data:res}=	await	this.$http.put(`roles/${this.roleId}`,this.EditRole)
				if(res.meta.status!==200) return this.$message.error('编辑角色失败')
				this.$message.success('编辑角色成功')
				this.getRolesList()
				this.EditDialogVisible=false
			},
			showEditDialog(row){
				console.log(row)
				this.roleId=row.id
				this.EditRole.roleDesc= row.roleDesc
				this.EditRole.roleName= row.roleName
				this.EditDialogVisible=true
			},
		async	showDeleteOpen(row){
			this.roleId=row.id
				 const Deleteresult=await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
				          confirmButtonText: '确定',
				          cancelButtonText: '取消',
				          type: 'warning'
				        }).catch(err=>err)
								if(Deleteresult!=='confirm') return this.$message.info('以取消删除')
					const {data:res}=	await	this.$http.delete(`roles/${this.roleId}`)	
					if(res.meta.status!==200) return this.$message.error('删除失败')
					this.$message.success('删除成功')
					this.getRolesList()
			},
			// 监听分配权限对话框的关闭事件
			setRightDialogClose(){
				this.defKeys=[]
			},
			// 展示分配权限的对话框
		async	showSetRightDialog(role){
			this.roleId=role.id
				//获取所有权限数据
		const {data:res} =	await	this.$http.get('rights/tree')
		if(res.meta.status!==200) return this.$message.info('获取权限数据失败')
		//把获取到的权限数据放到rightList中
		      this.rightList=res.data
					console.log(this.rightList)
					this.getLeafKeys(role,this.defKeys)
				this.setRightDialogVisible=true;
			},
			// 获取所有角色的列表
			async getRolesList(){
			const {data:res}=await	this.$http.get("roles")
			if(res.meta.status!==200) return this.$message.error("获取角色失败");
			this.roleList=res.data
		
			},
			// 为角色分配权限
		async	allotRights(){
				const keys=[
					...this.$refs.treeRef.getCheckedKeys(),
					...this.$refs.treeRef.getHalfCheckedKeys()
				]
				console.log(keys)
				const idStr=keys.join(',')
			const {data:res}=await	this.$http.post(`roles/${this.roleId}/rights`,{rids:idStr})
			if(res.meta.status!=200){
				return this.$message.info('分配权限失败')
			}
			this.$message.success('分配权限成功')
			this.getRolesList()
			this.setRightDialogVisible=false
			},
			// 根据ID删除对应的权限
			async removeRightById(userId,rightsId){
				//弹框提示用户是否要删除
				console.dir(rightsId)
				 const confirmResult= await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
				          confirmButtonText: '确定',
				          cancelButtonText: '取消',
				          type: 'warning'
				        }).catch(err=>err);
								if(confirmResult!='confirm') return this.$message.info('取消删除')
								const {data:res}=await this.$http.delete(`roles/${userId.id}/rights/${rightsId}`)
								if(res.meta.status!==200) return this.$message.info('删除失败')
								this.$message.success('删除成功')
								// this.getRolesList()
								userId.children=res.data
			},
			//通过递归的形式获得所有三级权限的ID 保存到DefKeys中
			getLeafKeys(node,arr){
				//如果当前node节点不包含children属性 则为三级节点
				if(!node.children){
					return arr.push(node.id)
				}else{
					node.children.forEach(item=>{
						this.getLeafKeys(item,arr)
					})
				}
			}
		}
	}
</script>

<style scoped="scoped" lang="less">
	.el-tag{
		margin: 7px;
	}
	.bdtop{
		border-top: 1px solid #eee;
	}
	.bdbottom{
		border-bottom: 1px solid #eee;
	}
	.vcenter{
		display: flex;
		// justify-content: center;
		align-items: center;
	}
</style>
